<?php
set_include_path('system'.PATH_SEPARATOR.'templates');

require_once('Template.php');
require_once('RedirectBrowserException.php');
require_once('DatabaseUtility.php');
require_once('CustomFunctions.php');

$tmpl = new Template();

$phosphosite_id = $_GET['id'];
$ref = $_GET['ref'];

$getref = "";
if (!empty($ref)) {
	$getref = '&ref='.$ref;
}

openDatabase();
$query  = "SELECT site.protein AS pid, protein.annotation, protein.sequence, organism.latin, organism.commonName, site.locationInProtein AS loc ".
          "FROM site,protein,organism ".
          "WHERE site.protein=protein.id AND protein.organism=organism.label AND site.ptm='p' AND site.id=".$phosphosite_id.";";
$rows = runQuery($query);

$id = $rows[0]['pid'];

// query dataSource
$query = "SELECT dataSource.id,dataSource.reference FROM dataSource,siteDataSourceRelation WHERE siteDataSourceRelation.site='".$phosphosite_id."' AND siteDataSourceRelation.dataSource=dataSource.id ORDER BY pubmed DESC";
$datasourceRows = runQuery($query);
foreach($datasourceRows as $row) {
	$dataSource[$row['id']] = $row['reference'];
}
if (count($dataSource)>1) {
	$dataSource[0] = "All";
	ksort($dataSource);
}

$loc = $rows[0]['loc'];
$sequence = $rows[0]['sequence'];
$start = 10*floor($loc/10)+1;
$end = 10*ceil($loc/10);
$surrSeq = substr($sequence,$start,$loc-$start).'<span class="ui-corner-all phosphosite">'.substr($sequence,$loc,1).'</span>'.substr($sequence,$loc+1,$end-$loc);

$mass = spectralOfProtein($id, $ref);

if (empty($ref)) {
	$query = "SELECT DISTINCT peptide.phosphoSequence, peptideSiteRelation.locationInPeptide, peptide.location ".
			 "FROM peptideSiteRelation,peptide ".
			 "WHERE peptideSiteRelation.site=$phosphosite_id AND peptideSiteRelation.peptide=peptide.id;";
} else {
	$query = "SELECT DISTINCT peptide.phosphoSequence, peptideSiteRelation.locationInPeptide, peptide.location ".
			 "FROM peptideSiteRelation,peptide,mass ".
			 "WHERE peptideSiteRelation.site=$phosphosite_id AND peptideSiteRelation.peptide=peptide.id AND peptide.mass=mass.id AND mass.dataSource=$ref;";
}

$peptides = array();
$nrPeptideRows = runQuery($query);
foreach($nrPeptideRows as $row) {
	$nrseq = $row['phosphoSequence'];
	$linkformat = str_replace('#', '%23', $nrseq);
	$formated = format_nr_pep_unlink_exclusiveself($nrseq,$row['locationInPeptide']);
	$href = 'href="peptide.php?pnrseq='.$linkformat.'&pro='.$id.'&loc='.$row['location'].$getref.'"';
	$peptides[$formated] = $href;
}

// reference links
$refs = array();
$query ="SELECT id,link,reference FROM dataSource ORDER BY pubmed DESC;";
$result = runQuery($query);
foreach($result as $row) {
	$refID = $row['id'];
	$link = $row['link'];
	if (empty($link)) {
			$refs[$refID] = $row['reference'];
	} else {
			$refs[$refID] = $link;
	}
}
if(!empty($ref)) $refLink = $refs[$ref];
else if (count($dataSource) == 1) {
	$refID = array_keys($dataSource);
	$refLink = $refs[$refID[0]];
}

$tmpl->peptides		= $peptides;
$tmpl->id 			= $phosphosite_id;
$tmpl->ref			= $ref;
$tmpl->refLink		= $refLink;
$tmpl->surrSeq		= $surrSeq;
$tmpl->loc 			= $loc + 1;
$tmpl->dataSource 	= $dataSource;
$tmpl->protLink		= 'protein.php?id='.$id.$getref;
$tmpl->accessions 	= getXrefLink($id);
$tmpl->description 	= $rows[0]['annotation'];
$tmpl->organism 	= '<i>'.$rows[0]['latin'].'</i> ('.$rows[0]['commonName'].')';
$tmpl->numSites 	= count($sites);
$tmpl->numSpectra 	= count($mass);
$tmpl->sequence 	= $rows[0]['sequence'];
closeDatabase();

$tmpl->current = 'browse';
$tmpl->pageContent = $tmpl->build('phosphosite.tmpl');

print $tmpl->build('page.tmpl');

function format_nr_pep_unlink_exclusiveself($nrpseq,$exsite) {
        $seq = "";
        $seqpep = str_replace('#', '', $nrpseq);

        $start = 0;

        $sites = getSiteFromNrPep($nrpseq);
        foreach($sites as $site) {
                if ($site == $exsite) {
                        $sbst = '<span class="ui-corner-all phosphosite highlight">'.substr($seqpep,$site,1).'</span>';
                } else {
                        $sbst = '<span class="ui-corner-all phosphosite">'.substr($seqpep,$site,1).'</span>';
                }
                $seq = $seq.substr($seqpep,$start,$site-$start).$sbst;
                $start = $site + 1;
        }
        $seq = $seq.substr($seqpep,$start);

        return $seq;
}

function getSiteFromNrPep($nrpseq) {
    $curr = strpos($nrpseq, '#');
    while ($curr) {
    	$sites[] = $curr - count($sites) - 1;
    	$curr = strpos($nrpseq, '#', $curr+1);
    }
    return $sites;
}
?>